'use strict';

/**
 * @ngdoc service
 * @name jgappApp.DeveiceIdService
 * @description
 * # DeveiceIdService
 * Service in the jgappApp.
 */
angular.module('jgappApp')
    .service('DeveiceIdService', ['$q', "$window", "$timeout", "DataService", "openApi", "Util", function($q, $window, $timeout, DataService, openApi, Util) {
        // AngularJS will instantiate a singleton by calling "new" on this function
        var DeveiceIdService = {}
        DeveiceIdService.getDeviceId = function() {
            var delay = $q.defer();
            var deviceId;
            deviceId = $window.localStorage.getItem("deviceId");
            if (deviceId) {
                $timeout(function() {
                    delay.resolve(deviceId);
                }, 100)
            } else {
                if (window.plugins) {
                    $window.plugins.jPushPlugin.getRegistrationID(function(id) {
                        $window.localStorage.setItem("deviceId", id);
                        delay.resolve(id);
                    })
                } else {
                    $timeout(function() {
                        delay.resolve("");
                    }, 100)
                }
            }
            return delay.promise;
        };
        DeveiceIdService.cleanDeviceId = function() {
            $window.localStorage.removeItem("deviceId");
        };
        DeveiceIdService.sendIdToServe = function() {
            var param = {};
            var clientType = Util.getPlatform() == "android" ? 1 : 2;
            param.clientType = clientType;
            DeveiceIdService.getDeviceId().then(function(id) {
            	console.log("geting deviceId...")
                if (id) {
                    param.clientId = id
                    param.noloader = true
                    DataService.getData(openApi.updateClientId, param).then(function(data) {});
                }
            });
        }
        return DeveiceIdService
    }]);
